package com.yxjx.duoxue;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.yxjx.duoxue.course.CourseIntroductionActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.course.CourseSearchActivity;
import com.yxjx.duoxue.course.SearchCondition;
import com.yxjx.duoxue.course.datamodel.HomeAllAdData;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMAdItem;
import com.yxjx.duoxue.datamodel.DMArea;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.datamodel.DMKeyword;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.message.ClientMessageListDTS;
import com.yxjx.duoxue.message.MessageListActivity;
import com.yxjx.duoxue.message.UnreadStatus;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * 所有页面通用的加载页面。
 * @author mengmengchen
 *
 */
public class PageLoading extends BaseActionBarActivity {
	public static final String EXTRA_INTENT = "EXTRA_INTENT";
	public static final int LOAD_PAGE = 0;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// customize actionbar
		Intent intent = (Intent) getIntent().getExtras().getParcelable(EXTRA_INTENT);
		extraIntent = intent;
		final String targetClassName = "" + extraIntent.getComponent().getClassName();
		if (targetClassName.equals(CourseListActivity.class.getName())) {
//			setCustomActionBar(R.layout.head_course_list_both);
		} else {
		}
		
		setContentView(R.layout.loading);
		
		if (targetClassName.equals(CourseListActivity.class.getName())) {
//			mActionBar.getCustomView().findViewById(R.id.search_course).setSelected(true);
//			mActionBar.getCustomView().findViewById(R.id.search_school).setSelected(false);
		} else {
			customizeActionBarTitle("");
		}
		
		
		// 设置一个progressdialog的弹窗
//		dialog = ProgressDialog.show(this, "加載中...", "正在努力加载，請稍後！");
		Thread thread = new Thread(new Runnable() {
			public void run() {
				if (targetClassName.equals(HomePageActivity.class.getName())) {
//					getCurrentLocation(PageLoading.this);
//					getAllAds();
//					getRecommendCourses(PageLoading.this);
				} else if (targetClassName.equals(CourseListActivity.class.getName())) {
//					getAreasInfo(PageLoading.this);
//					getCourseCategory(PageLoading.this);
//					getSortBys(PageLoading.this);
				} else if (targetClassName.equals(CourseSearchActivity.class.getName())) {
//					getHotKeywords();
//					getSearchHistory(PageLoading.this);
				}
				
				Message message = new Message();
				message.what = LOAD_PAGE;
				mHandler.sendMessage(message);
			}
		});
		thread.setPriority(Thread.MAX_PRIORITY);
		thread.start();

	}

	// 处理跳转到主Activity
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			startActivity(extraIntent);
			PageLoading.this.finish();
			overridePendingTransition(0, 0);
			
//			if (msg.what == LOAD_PAGE) {
//				dialog.dismiss();
//			}
		}
	};
	private Intent extraIntent;
	
	public static boolean getCourseCategory(Context context) {
		try {
			ArrayList<ArrayList<DMCourseCategory>> courseTypes = Globals.getInstance(context).getCourseTpes();
			if (courseTypes == null) {
				courseTypes = NwUtils.requestCourseCategories(context);
				Globals.getInstance(context).setCourseTypes(courseTypes);
				/// START 存一分一维数组的详细课程分类，用于在课程分类详情页面展示。
				if (courseTypes == null) {
					return false;
				}
				ArrayList<DMCourseCategory> array = new ArrayList<DMCourseCategory>();
				for (ArrayList<DMCourseCategory> items : courseTypes) {
					if (items != null && items.size() > 1) {
						array.add(items.get(0));
					}
				}
				Globals.getInstance(context).setDetailedCourseTypes(array);
				/// END
			}
			return true;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 获取所有的sort by信息，并保存到AppDataModel
	 * @param context
	 * @return
	 */
	public static boolean getSortBys(Context context) {
		if (Globals.getInstance(context).getSortBysCourse() != null
				&& Globals.getInstance(context).getSortBysSchool() != null) {
			return true;
		}
		try {
			ResponseObject code = NwUtils.requestSortBys(context);
			return code.getCode() == MsgCode.SUCCESS;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean getAreasInfo(Context context) {
		try {
			ArrayList<ArrayList<DMArea>> areas = Globals.getInstance(context).getAreasInfo() ;
			if (areas == null) {
				areas = NwUtils.requestAllAreas(828, context);
				Globals.getInstance(context).setmAreasInfo(areas);
			}
			return true;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean getAllAds(Context context) {
		return getAllAdsForce(context, false);
	}
	
	/**
	 * 获取广告列表信息
	 * @param context
	 * @param force
	 * @return
	 */
	public static boolean getAllAdsForce(Context context, boolean force) {
		HomeAllAdData ads = null;
		try {
			ads = Globals.getInstance(context).getAllAdsData();
			if (ads == null || force) {
				ads = NwUtils.requestAdList(context);
				Globals.getInstance(context).setAllAdsData(ads);
			}
			return true;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 加载首页的九宫格课程分类列表
	 * @param context
	 * @return
	 */
	public static boolean getHomeCourseCategory(Context context) {
		ArrayList<DMCourseCategory> categories = null;
		try {
			categories = Globals.getInstance(context).getHomeCourseCategories();
			if (categories == null) {
				categories = NwUtils.requestHomeCourseCategories(context);
				Globals.getInstance(context).setHomeCourseCategories(categories);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean getHotKeywords(Context context) {
		try {
			ArrayList<DMKeyword> keywords = Globals.getInstance(context).getKeywords();
			if (keywords == null) {
				keywords = NwUtils.requestSearchKeywords(context);
				Globals.getInstance(context).setKeywords(keywords);
			}
			return true;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}

	// 加载搜索历史
	public static boolean getSearchHistory(Context context) {
		ArrayList<String> searchHistory = Globals.getInstance(context).getSearchHistory();
		if (searchHistory == null) {
			YxDataBase db = YxDataBase.getInstance(context);
			Globals.getInstance(context).setSearchHistory(db.getSearchHistory());
		}
		return true;
	}

	// 增加课程推荐
	public static boolean getRecommendCourses(Context context) {
		return getRecommendCoursesForce(context, false);
	}
	
	// 
	public static boolean queryNewMessages(Context context) {
		JSONObject params = new JSONObject();
		try {
			params.put("date", System.currentTimeMillis());
			
//			boolean resultFromWeb = UserReg.checkNewMessageAvaiable(params, context);
			ArrayList<ClientMessageListDTS> newMessages = MessageListActivity.requestMessagesList(context);
			boolean resultFromDB = YxDataBase.getInstance(context).queryHasMessageNoVisited(newMessages);
			
			Globals data = Globals.getInstance(context);
			if (data.getUnread() == null) {
				data.setUnread(new UnreadStatus());
				data.getUnread().setHasNewMessage(resultFromDB);
			}
			
			return resultFromDB;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 获取推荐课程列表
	 * @param context
	 * @param force
	 * @return
	 */
	public static boolean getRecommendCoursesForce(Context context, boolean force) {
		ArrayList<DMCourse> courses = Globals.getInstance(context).getRecommendCourses();
		if (courses == null || force) {
			try {
				courses = NwUtils.requestDataInfoList(NwUtils.REQ_COURSE_LIST,
						SearchCondition.getRecommendCoursesParam(),
						UserLoginResponse.getInstance(context), context);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Globals.getInstance(context).setRecommendCourses(courses);
		}
		return true;
	}

	//
	public static boolean getCurrentLocation(Context context) {
		long start = System.currentTimeMillis();
		while (true && (System.currentTimeMillis() - start) < 1 * 2000) {
			DMBaiduLocation location = DMBaiduLocation.getLocation(context);
			if (location != null) {
				return true;
			} else {
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		Utils.logd("获取位置信息失败或者超时");
		return true;
	}
}

